---
import SvelteWrapper from './SvelteWrapper.svelte'
import Code from '../Code/Code.astro'
import CodeWrapper from './CodeWrapper.svelte'
import { getAllExamplesModules } from './globLoader'

interface Props {
  /**
   * The path to the entry App.svelte file relative to src/examples
   */
  path: string
  hideCode?: boolean
  hidePreview?: boolean
  iframe?: boolean
  showFile?: string
  expandCode?: boolean
  previewClass?: string
  hideStackblitz?: boolean
}

const allModules = getAllExamplesModules()

const filteredModules = Object.fromEntries(
  Object.entries(allModules).filter(([key]) => {
    return key.replace('../../examples/', '').startsWith(Astro.props.path + '/')
  })
)

const files: Record<string, string> = {}
for (const path in filteredModules) {
  let relativePath = path.replace('../../examples/', '').replace(Astro.props.path, '').slice(1)
  if (relativePath.startsWith('/')) {
    relativePath = relativePath.slice(1)
  }
  files[relativePath] = filteredModules[path] as string
}

const hideCode = Astro.props.hideCode ?? false
const hidePreview = Astro.props.hidePreview ?? false
---

<>
  {
    !hidePreview && (
      <SvelteWrapper
        hideStackblitz={Astro.props.hideStackblitz}
        class={Astro.props.previewClass}
        hideCode={hideCode}
        path={Astro.props.path}
        client:load
        files={files}
        iframe={Astro.props.iframe ?? true}
      />
    )
  }

  {
    !hideCode && (
      <CodeWrapper
        showFile={Astro.props.showFile}
        exampleBasePath={Astro.props.path}
        expanded={hidePreview || (Astro.props.expandCode ?? false)}
        hidePreview={hidePreview}
        client:load
        filePaths={Object.keys(filteredModules).map((path) =>
          path.replace('../../examples/', '').replace(Astro.props.path, '').slice(1)
        )}
      >
        {Object.entries(filteredModules).map(([path, mod]) => (
          <div
            data-path={path}
            class="h-full"
          >
            <Code
              code={mod}
              lang={(path.split('.').pop() ?? 'svelte') as any}
              class="mb-0! mt-0! h-full rounded-none border-none"
            />
          </div>
        ))}
      </CodeWrapper>
    )
  }
</>
